from dto.strategy_calculate_result import StrategyCalculateResult
from service.das.stock_assessment_das import RiskAssessmentService
from service.das.stock_assessment_item_das import RiskAssessmentItemService


class StrategyViewQueryService:

    def searchFinalResult(self, stock_code: str) -> StrategyCalculateResult:
        """
        聚合查询，返回 StrategyCalculateResult 对象
        :param stock_code: 股票代码
        :return: 聚合的 StrategyCalculateResult
        """
        try:

            riskService = RiskAssessmentService()
            riskItem = RiskAssessmentItemService()

            # 查询 AntRiskAssessmentModel 的股票信息

            stock_record = riskService.get_risk_assessment_by_code(stock_code)
            stock_info = AntMonitorStock(
                stock_code=stock_record.stock_code,
                create_time=stock_record.create_time,
                description=stock_record.description,
                risk_type=stock_record.risk_type,
                risk_level=stock_record.risk_level,
                stock_hold_ratio=stock_record.stock_hold_ratio,
                future_action=stock_record.future_action,
                stock_tag_code=stock_record.stock_tag_code,
                stock_tag_desc=stock_record.stock_tag_desc,
                final_point=stock_record.final_point,
            )

            # 查询 AntRiskAssessmentItem 的风险评估记录
            risk_items = AntRiskAssessmentItem.select().where(
                AntRiskAssessmentItem.stock_code == stock_code
            )
            risk_assessments = [
                RiskAssessment(
                    stock_code=item.stock_code,
                    description=item.description,
                    risk_type=item.risk_type,
                    risk_level=item.risk_level,
                    stock_tag_code=item.stock_tag_code,
                    strategy_code=item.strategy_code,
                    strategy_name=item.strategy_name,
                    strategy_group=item.strategy_group,
                    strategy_type=item.strategy_type,
                    analysis_day=item.analysis_day,
                    strategy_level=item.strategy_level,
                    node_point=item.node_point,
                )
                for item in risk_items
            ]

            # 聚合结果
            result = StrategyCalculateResult(
                stock_info=stock_info,
                risk_assessments=risk_assessments,
                total_score=sum(item.node_point or 0 for item in risk_assessments),
                risk_level=max(
                    (item.risk_level or 0 for item in risk_assessments), default=1
                ),
                focus_level=max(
                    (item.strategy_level or 0 for item in risk_assessments), default=1
                ),
            )
            return result
        except Exception as e:
            print(f"查询时出错: {e}")
            return StrategyCalculateResult()
